//
//  BottonTimer.swift
//  jiaoyi
//
//  Created by wjk on 2018/8/19.
//  Copyright © 2018年 wjk. All rights reserved.
//

import UIKit
import Foundation

struct XKeys {
    static var common : NSInteger = 60
}

extension UIButton {
    
    var common : NSInteger {
        get{
            return objc_getAssociatedObject(self, &XKeys.common) as! NSInteger
        }
        set{
            objc_setAssociatedObject(self, &XKeys.common, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    
    
    
    func startTimer(title: String) {
        self.isEnabled = false
        common = 60
        Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.cuntDown(_:)), userInfo: nil, repeats: true).fire()
    }
    
    func stopTimer(title: String) {
        self.isEnabled = true
        common = 0
        
    }
    
    @objc private func cuntDown(_ time:Timer) {
        common = common - 1
        
        if common <= 0 {
            self.isEnabled = true;
            time.invalidate()
//            time = nil
        }else {
            
            self.setTitle(String(format: "%d s", common), for: UIControlState.disabled)
        }
        
    }
    
}
